package com.wondream.myframework.app.common.environment;

import com.google.common.collect.Maps;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Spring环境变量初始化
 */
public class CfssSpringApplicationRunListener implements SpringApplicationRunListener {

    private final SpringApplication springApplication;

    private final String[] args;

    private final SimpleApplicationEventMulticaster initalMulticaster;

    private final String CFSS_EXT = "CFSS_EXT";

    public CfssSpringApplicationRunListener(SpringApplication springApplication, String args[]){
        this.springApplication = springApplication;
        this.args = args;
        this.initalMulticaster = new SimpleApplicationEventMulticaster();
        springApplication.getListeners().forEach(applicationListener -> {
            this.initalMulticaster.addApplicationListener(applicationListener);
        });
    }

    @Override
    public void starting() {

    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        // 1.禁用swagger安全机制
        Map<String, Object> map = Maps.newHashMap();
        map.put("swagger.auth.enabled", false);
        MapPropertySource mapPropertySource = new MapPropertySource(CFSS_EXT, map);
        environment.getPropertySources().addFirst(mapPropertySource);

        // 2.apollo饥饿家在，防止有些依赖apollo的配置的加载过早报错
        Properties eagerLoadEnabledProperties = new Properties();
        eagerLoadEnabledProperties.setProperty("apollo.bootstrap.eagerLoad.enabled", "true");
        System.setProperties(eagerLoadEnabledProperties);
        Properties bootstrapEnabledProperties = new Properties();
        bootstrapEnabledProperties.setProperty("apollo.bootstrap.enabled", "true");
        System.setProperties(bootstrapEnabledProperties);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {

    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {

    }

    @Override
    public void started(ConfigurableApplicationContext context) {

    }

    @Override
    public void running(ConfigurableApplicationContext context) {

    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {

    }
}
